package com.tdcy.framework.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.tdcy.framework.BusiContext;
import com.tdcy.framework.util.RequestUtils;
import com.tdcy.framework.util.SessionUtils;
import com.tdcy.sys.constant.AppConstants;
import com.tdcy.sys.service.bean.LoginInfoBean;

public class LoginHandlerInterceptor extends HandlerInterceptorAdapter {
	private static Logger log = LoggerFactory.getLogger(LoginHandlerInterceptor.class);

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		String url = request.getRequestURL().toString();
		String uri = request.getServletPath();

		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";

		BusiContext.setContext(AppConstants.BUSI_REQUESTURI, uri);
		BusiContext.setContext(AppConstants.BUSI_REQUESTURL, url);
		BusiContext.setContext(AppConstants.BUSI_PATH, path);
		BusiContext.setContext(AppConstants.BUSI_BASEPATH, basePath);

		Object obj = SessionUtils.getSesion(request.getSession(), AppConstants.SESSION_LOGIN_INFO);
		if (obj != null) {
			LoginInfoBean loginInfo = (LoginInfoBean) obj;
			BusiContext.setContext(AppConstants.BUSI_LOGIN_INFO, loginInfo);
			log.debug("用户[" + loginInfo.getUserEO().getUserName() + "]执行操作：" + "Method-" + request.getMethod() + ":" + url+ ((request.getQueryString() == null) ? "" : "?" + request.getQueryString()));
			log.debug("请求参数：" + RequestUtils.getAllParameters(request));
		}

		Object logineo = SessionUtils.getSesion(request.getSession(), AppConstants.SESSION_LOGIN_EO);
		if (logineo != null) {
			BusiContext.setContext(AppConstants.BUSI_LOGIN_EO, logineo);
		}
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
}
